package net.pugsplace.gpremacy.state;

import java.io.Serializable;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

public class Player implements Serializable {
	private static final long serialVersionUID = 835798242164592785L;
	private String name;
	// TODO: Shouldn't send this to the clients... refactor it out
	private byte[] passcodeDigest;

	public Player() {
		name = "Default Player";
	}

	public String getName() {
		return name;
	}

	public void setName(String newName) {
		name = newName;
	}

	/** Tries to store the user's passcode as a SHA256 hash; the
	 * fail-safe mode stores the actual passcode */
	public void setPasscode(String plaintext) {
		try {
			MessageDigest md = MessageDigest.getInstance("SHA256");
			passcodeDigest = md.digest(plaintext.getBytes());
		} catch (NoSuchAlgorithmException e) {
			passcodeDigest = plaintext.getBytes();
		}
	}

	public boolean validatePasscode(String plaintext) {
		try {
			MessageDigest md = MessageDigest.getInstance("SHA256");
			byte hash[] = md.digest(plaintext.getBytes());
			return Arrays.equals(passcodeDigest, hash);
		} catch (NoSuchAlgorithmException e) {
			byte bytes[] = plaintext.getBytes();
			return Arrays.equals(passcodeDigest, bytes);
		}
	}
}
